<template>
  <el-dialog
    title="Edit Members"
    width="800px"
    v-bind="$attrs"
    custom-class="authority-dialog"
    v-on="$listeners"
    @close="handleClose"
    @open="handleOpen"
  >
    <div class="p-2">
      <el-card shadow="never">
        <el-row>
          <el-col :span="12" style="padding: 20px">
            <el-input
              v-model="keyword"
              :placeholder="$t('page.search')"
              prefix-icon="el-icon-search"
              size="small"
            />
            <div v-show="!keyword" class="select-all">
              <el-checkbox
                v-model="selectAll"
                :indeterminate="isIndeterminate"
                @change="handleSelectAll"
              />
              <span class="ml-5">Select all</span>
            </div>
            <el-checkbox-group
              v-model="selectedMembers"
              style="height: 300px"
              @change="handleSelectMembersChange"
            >
              <el-scrollbar
                style="height: 100%"
                wrap-style="overflow-x:hidden;"
              >
                <ul
                  v-loading="loading"
                  class="member-list"
                  :style="{ height: loading ? '300px' : 'auto' }"
                >
                  <li
                    v-for="(member, index) in _members"
                    :key="member.userId"
                    class="member"
                    :style="index === members.length - 1 ? { margin: 0 } : {}"
                  >
                    <el-checkbox :label="member">
                      <div class="avatar-outer">
                        <img :src="_avatar(member.logoUrl)" class="avatar" />
                      </div>
                      {{ member.username }}
                    </el-checkbox>
                  </li>
                </ul>
              </el-scrollbar>
            </el-checkbox-group>
          </el-col>
          <div
            style="
              height: 100%;
              width: 1px;
              background-color: rgb(229, 231, 235);
              position: absolute;
              left: 50%;
            "
          />
          <el-col :span="12" style="padding: 20px">
            <div>
              <span style="line-height: 30px"
                >Selected: {{ selectedMembers.length }}
                {{ selectedMembers.length > 1 ? 'members' : 'member' }}</span
              >
            </div>
            <div style="height: 350px">
              <el-scrollbar
                style="height: 100%"
                wrap-style="overflow-x:hidden;"
              >
                <ul class="member-list">
                  <li
                    v-for="(member, index) in selectedMembers"
                    :key="member.userId"
                    class="member selected-members"
                  >
                    <div class="avatar-outer">
                      <img :src="_avatar(member.logoUrl)" class="avatar" />
                    </div>
                    <span class="flex-1">
                      {{ member.username }}
                    </span>
                    <i
                      class="el-icon-close remove-member"
                      @click="() => removeMember(index)"
                    />
                  </li>
                </ul>
              </el-scrollbar>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <template #footer>
      <div>
        <el-button
          type="primary"
          size="small"
          :loading="loading"
          @click="confirm"
          >{{ $t('common.confirm') }}</el-button
        >
      </div></template
    >
  </el-dialog>
  <!-- <el-dialog
    v-bind="$attrs"
    title="Edit Member"
    width="30%"
    custom-class="authority-dialog"
    v-on="$listeners"
    @close="handleClose"
    @open="handleOpen"
  >
    <div class="dialog-body">
      <div class="input-box">
        <el-input
          v-model="keyword"
          prefix-icon="el-icon-search"
          size="small"
          :placeholder="$t('common.search')"
          @keyup.native="search"
        />
      </div>
      <div class="select-all">
        <span>Select all</span>
        <el-checkbox v-model="selectAll" :indeterminate="isIndeterminate" @change="handleSelectAll" />
      </div>

      <el-checkbox-group v-model="selectedMembers" style="height: 300px;" @change="handleSelectMembersChange">
        <el-scrollbar style="height: 100%" wrap-style="overflow-x:hidden;">
          <ul v-loading="loading" class="member-list">
            <li
              v-for="(member, index) in members"
              :key="member.userId"
              class="member"
              :style="index === members.length - 1 ? { margin: 0 } : {}"
            >

              <div class="avatar-outer">
                <img :src="_avatar(member.logoUrl)" class="avatar">
              </div>
              <el-checkbox :label="member">
                {{ member.username }}
              </el-checkbox>
            </li>

          </ul>
        </el-scrollbar>
      </el-checkbox-group>

    </div>
    <div slot="footer">
      <span class="footer-selected-members">Selected: {{ selectedMembers.length }} {{ selectedMembers.length > 1 ?
        'members' : 'member' }}</span>
      <el-button type="primary" size="small" :loading="loading" @click="confirm">{{ $t('common.confirm') }}</el-button>
    </div>
  </el-dialog> -->
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getParameterAuthority,
  setAuthorityControl,
  getUsers
} from '@/api/parameter'
import { debounce } from '@/utils'
import { avatar } from '../helper'

export default {
  props: {
    templateId: String,
    tableId: String,
    paramId: String,
    param: Object,
    permissionAssignedUsers: Array || null
  },
  data() {
    return {
      keyword: '',
      members: [],
      selectedMembers: [],
      loading: false,
      isIndeterminate: false
    }
  },
  computed: {
    ...mapGetters(['avatars']),
    _members() {
      return this.members.filter(
        (member) => member.username.indexOf(this.keyword) > -1
      )
    },
    selectAll() {
      return this.selectedMembers.length === this.members.length
    }
  },
  mounted() {},
  methods: {
    async confirm() {
      if (this.param.new) {
        this.param.selectAllMembers = this.selectAll
        this.$emit(
          'update',
          this.selectedMembers.map((_) => ({
            userId: _.userId,
            userName: _.username
          }))
        )
        this.$emit('update:model-value', false)
      } else {
        this.loading = true
        try {
          const selectedMembers =
            this.selectedMembers.length === this.members.length
              ? []
              : this.selectedMembers.map((_) => ({
                  userId: _.userId,
                  userName: _.username
                }))
          await setAuthorityControl(
            this.templateId,
            this.tableId,
            this.paramId,
            selectedMembers
          )
          this.loading = false
          this.$message.success(this.$t('common.message.operation_success'))
          this.$emit('update', this.selectedMembers)
          this.$emit('update:model-value', false)
        } catch (err) {
          this.$message.error(err)
          this.loading = false
        }
      }
    },
    async fetchParameterAuthority(keyword) {
      try {
        this.loading = true
        const res = await getParameterAuthority(
          this.templateId,
          this.tableId,
          this.paramId,
          keyword
        )
        this.members = res
        this.selectedMembers = res.filter((_) => _.paramPermissionControl === 1)
        this.loading = false
      } catch (err) {
        this.loading = false
        this.$message.error(err)
      }
    },
    // search() {
    //   if (this.keyword) {
    //     this.members = this.members.filter(member => member.username.indexOf(this.keyword) > -1)
    //   } else {
    //     this.members
    //   }
    // },
    // search: debounce(async function() {
    //   if (this.param.new) {
    //     this.members = await getUsers(this.keyword)
    //   } else {
    //     this.fetchParameterAuthority(this.keyword)
    //   }
    // }, 500),
    // 从头像库中找到用户对应的头像
    _avatar(logoUrl) {
      return avatar(this.avatars, logoUrl)
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data())
    },
    handleOpen() {
      this.$nextTick(async () => {
        if (this.param.new) {
          this.members = await getUsers()
        } else {
          this.fetchParameterAuthority()
        }
      })
    },
    handleSelectAll(checked) {
      this.selectedMembers = checked ? [...this.members] : []
      this.isIndeterminate = false
    },
    handleSelectMembersChange(checked) {
      const checkedCount = checked.length
      // this.selectAll = checkedCount === this._members.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this._members.length
    },
    removeMember(index) {
      this.selectedMembers.splice(index, 1)
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep {
  .el-dialog__body,
  .el-card__body {
    padding: 0 !important;
  }
}

.dialog-body {
  padding: 10px;

  &::v-deep {
    .el-checkbox {
      flex: 1 1;
      line-height: 45px;

      .el-checkbox__input {
        float: right;
        line-height: 45px;
      }
    }
  }
}

.select-all {
  display: flex;
  padding: 0 14px;
  align-items: center;

  span {
    line-height: 45px;
  }
}

.member-list {
  padding: 10px;

  .member {
    display: flex;
    align-items: center;
    transition: background-color 0.15s ease;
    border-radius: 4px;
    padding: 8px 4px;
    cursor: pointer;
    &:hover {
      background-color: #ededee;
    }

    &:not(:last-child) {
      margin-bottom: 6px;
    }

    .avatar-outer {
      display: inline-block;
      width: 45px;
      height: 45px;
      @apply mr-2;
      .avatar {
        border-radius: 50%;
      }
    }
  }
  .remove-member {
    color: #909399;
    padding: 2px;
    background-color: transparent;
    transition: background-color 0.15s ease;
    border-radius: 4px;
    &:hover {
      background-color: #d7d8d9;
    }
  }
}

.footer-selected-members {
  float: left;
  line-height: 30px;
}
</style>
